package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author zlr
 * @since 2024-11-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> treeSelect(Long parentId) {
        //根据parentId查找子节点
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, parentId);
        List<Category> categoryList = baseMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(category -> {
                //查找当前节点是否有子节点
                Long count = baseMapper.selectCount(
                        new LambdaQueryWrapper<Category>()
                                .eq(Category::getParentId, category.getId())
                );
                category.setHasChildren(count > 0);
            });
        }
        return categoryList;
    }
}
